package cn.icyzx.service;

import cn.icyzx.dao.DaoUser;
import cn.icyzx.dao.DaoWorks;
import cn.icyzx.exception.WorkException;
import cn.icyzx.models.Comment;
import cn.icyzx.models.Work;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.icyzx.util.CommonUtil;
import cn.icyzx.util.StaticConstUtil;

import java.util.*;

/**
 * Created by 郑凯 on 2016/9/1.
 */
@Service
@Transactional
public class WorkService {

    private static Logger logger = Logger.getLogger(WorkService.class);

    @Autowired
    DaoWorks daoWorks;

    @Autowired
    DaoUser daoUser;

    @Autowired
    TagService tagService;

    public Work getWorkByWid(String wid) {
        Work work = null;
        try {
            work = daoWorks.getWorkByWid(wid);
        } catch (WorkException e) {
            logger.error(e.getMessage());
        }
        return work;
    }

    public Work getWorkByWid(String wid, String uid) {
        Work work = null;
        try {
            work = daoWorks.getWorkByWid(wid);
            String time = CommonUtil.getTimeAgo(work.getPublicTime().getTime());
            work.setAgo(time);
        } catch (WorkException e) {
            logger.error(e.getMessage());
        }
        return work;
    }

    public boolean addWorkOperate(String wid, String uid, String type) {
        return daoWorks.addWorkOperate(wid, uid, type);
    }


    public Integer getWorksPageSum(Map<String, String> condition) {
        int worksSum = daoWorks.getWorksSum(condition);
        int pageSize = StaticConstUtil.PAGE_SIZE;

        return worksSum % pageSize == 0 ? worksSum / pageSize : (worksSum / pageSize + 1);
    }

    public Map<String, String> getWorkOperateStatus(String wid, String uid) {
        Map<String, String> workOperateStatus = new HashMap<String, String>();
        if (daoWorks.isRecommend(wid, uid))
            workOperateStatus.put("recommend", "true");
        else
            workOperateStatus.put("recommend", "false");

        if (daoWorks.isCollection(wid, uid))
            workOperateStatus.put("collection", "true");
        else
            workOperateStatus.put("collection", "false");
        return workOperateStatus;
    }

    public List<Work> getlistWorks(Map<String, String> condition) {
        try {
            return daoWorks.getListWorks(condition);
        } catch (WorkException workExeception) {
            logger.error("sql 语句拼装错误");
            workExeception.printStackTrace();
            return null;
        }
    }

    /**
     * 增加帖子浏览次数
     *
     * @param wid
     */
    public void over(String wid) {
        try {
            daoWorks.over(wid);
        } catch (WorkException e) {
            logger.error(e.getMessage());
        }
    }

    public boolean commentWork(String wid, String uid, String info) {
        return daoWorks.commentWork(wid, uid, info);
    }

    public List<Comment> getlistCommentsByWid(String wid) {
        return daoWorks.getlistCommentsByWid(wid);
    }

    /**
     * 添加一个新的帖子
     *
     * @param jsonWork
     */
    @Transactional
    public void insertWork(JSONObject jsonWork) {
        jsonWork.put("wid", String.valueOf(new Date().getTime()));
        JSONArray tags = (JSONArray) jsonWork.get("tags");
        try {
            for (Object tag : tags) {
                if (tagService.getTagByTagName((String) tag) == null) {
                    tagService.addTag((String) tag); //添加新标签
                }
                tagService.addWorkTagRecord((String) jsonWork.get("wid"), (String) tag); //添加一条标签记录
            }
            daoWorks.insertWork(jsonWork);
        } catch (WorkException workExeception) {
            logger.error(workExeception.getMessage() + "添加work错误");
        }
    }

    public List<Work> getHotWork() {
        try {
            return daoWorks.getHotWork();
        } catch (WorkException e) {
            logger.error(e.getMessage() + "获取近期热议错误");
            return null;
        }
    }

    /**
     * 获取用户的作品个数，评论个数，收藏个数，推荐个数（如果不加多余的字段只能这么做，
     * 如果加了多余的字段，每次都要更新，实在纠结，哪个更好）
     *
     * @param uid
     * @return
     */
    public Map<String, Integer> getOperatorWorkNumberByUid(String uid) {
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("workNumber", daoWorks.getWorksNumberByUid(uid));
        map.put("commentNumber", daoWorks.getCommentsNumberByUid(uid));
        map.put("collectionNumber", daoWorks.getCollectionNumberByUid(uid));
        map.put("recommendNumber", daoWorks.getRecommendNumberByUid(uid));
        return map;
    }
}
